import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:netease_music/component/DoPlayControl.dart';
import 'package:netease_music/main.dart';
import 'package:provider/provider.dart';

import '../playService.dart';

class MainPage extends StatefulWidget {
  final Widget child;

  const MainPage({super.key, required this.child});

  @override
  State<MainPage> createState() => _HomePageState();
}

class _HomePageState extends State<MainPage> {
  int currentDurationSec = 0;
  int currentTotalDuration = 100;

  @override
  void initState() {
    super.initState();
    playService.onPlayerComplete.listen((event) {
      context.read<CurrentProvider>().updateIcon(Icons.play_arrow_outlined);
      context.read<CurrentProvider>().playNext();
    });
    playService.onPlayerStateChanged.listen((state) {
      print('$state');
      if (state == PlayerState.playing) {
        context.read<CurrentProvider>().updateIcon(Icons.pause_circle_outline);
      }
      if (state == PlayerState.paused) {
        context.read<CurrentProvider>().updateIcon(Icons.play_arrow_outlined);
      }
    });
    playService.onDurationChanged.listen((Duration duration) {
      if (duration.inSeconds != currentTotalDuration) {
        currentTotalDuration = duration.inSeconds;
        context
            .read<CurrentProvider>()
            .updateTotalDuration(currentTotalDuration);
      }
    });
    playService.onPositionChanged.listen((Duration duration) {
      if (duration.inSeconds != currentDurationSec) {
        currentDurationSec = duration.inSeconds;
        context.read<CurrentProvider>().updatePosition(currentDurationSec);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: AnimatedContainer(
        decoration: context.watch<CurrentProvider>().decoration,
        curve: Curves.fastOutSlowIn,
        duration: const Duration(seconds: 1),
        child: Stack(
          children: [
            Padding(
              padding: const EdgeInsets.only(bottom: 80),
              child: widget.child,
            ),
            const DoPlayControl(),
          ],
        ),
      ),
    );
  }
}
